package cn.com.pc.content.controller;

import cn.com.pc.content.annotation.LogRequired;
import cn.com.pc.content.domain.Biz;
import cn.com.pc.content.domain.Site;
import cn.com.pc.content.domain.tag.TagGroup;
import cn.com.pc.content.dto.PageForm;
import cn.com.pc.content.dto.PageResult;
import cn.com.pc.content.dto.Sort;
import cn.com.pc.content.dto.TagGroupDTO;
import cn.com.pc.content.service.TagGroupService;
import cn.com.pc.content.util.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 标签组/标签聚合管理
 *
 */
@RestController
@RequestMapping("/tag-groups")
@Slf4j
public class TagGroupController {

    @Autowired
    private TagGroupService tagGroupService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 新增标签组
     * @param site
     * @param biz
     * @param tagGroupDTO
     * @return
     */
    @PostMapping
    @LogRequired(operation = "'新增标签组' + #_return")
    public Long createTagGroup(@RequestAttribute("site") Site site, @RequestAttribute("biz") Biz biz, @Validated @RequestBody TagGroupDTO tagGroupDTO) {
        // 查重
        if (tagGroupService.existsTagGroupByName(site, biz, tagGroupDTO.getName())) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "标签组已存在");
        }

        tagGroupDTO.setSite(site);
        tagGroupDTO.setBiz(biz);
        tagGroupDTO.setCreatedAt(LocalDateTime.now());
        tagGroupDTO.setUpdatedAt(LocalDateTime.now());
        return tagGroupService.createTagGroup(tagGroupDTO);
    }


    /**
     * 查询标签组列表
     * @param site
     * @param biz
     * @param tagGroupDTO
     * @param pageForm
     * @param sort
     * @return
     */
    @GetMapping
    public PageResult<TagGroup> listTagGroupsByDTO(@RequestAttribute("site") Site site, @RequestAttribute(value = "biz", required = false) Biz biz, TagGroupDTO tagGroupDTO, PageForm pageForm, Sort sort) {
        tagGroupDTO.setSite(site);
        tagGroupDTO.setBiz(biz);
        return tagGroupService.listTagGroupsByDTO(tagGroupDTO, pageForm, sort);
    }


    /**
     * 查询标签组详情
     * @param tagGroupId
     * @return
     */
    @GetMapping("/{tagGroupId:\\d+}")
    public TagGroup getTagGroupById(@RequestAttribute("site") Site site, @PathVariable("tagGroupId") Long tagGroupId) {
        TagGroup tagGroup = tagGroupService.getTagGroupById(tagGroupId);
        if (tagGroup == null || tagGroup.getSite() != site) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "标签组不存在");
        }
        return tagGroup;
    }


    /**
     * 修改标签组
     * @param site
     * @param biz
     * @param tagGroupDTO
     * @param tagGroupId
     * @return
     */
    @PutMapping("/{tagGroupId:\\d+}")
    @LogRequired(operation = "'修改标签组' + #tagGroupId")
    public TagGroup updateTagGroupByDTO(@RequestAttribute("site") Site site, @RequestAttribute("biz") Biz biz, @Validated @RequestBody TagGroupDTO tagGroupDTO, @PathVariable("tagGroupId") Long tagGroupId) {
        TagGroup tagGroup = tagGroupService.getTagGroupById(tagGroupId);
        if (tagGroup == null || tagGroup.getSite() != site) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "标签组不存在");
        }

        // 查重
        if (!tagGroupDTO.getName().equals(tagGroup.getName())) {
            if (tagGroupService.existsTagGroupByName(site, biz, tagGroupDTO.getName())) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "标签组已存在");
            }
        }

        tagGroupDTO.setSite(site);
        tagGroupDTO.setBiz(biz);
        tagGroupDTO.setUpdatedAt(LocalDateTime.now());
        try {
            request.setAttribute("operation", "，修改属性" + BeanUtils.comparePropertyIgnore(tagGroup, tagGroupDTO, "id", "createdAt", "updatedAt", "tags"));
        } catch (Exception e) {
            log.warn("标签组{}生成修改日志有误", tagGroupId);
            e.printStackTrace();
        }
        return tagGroupService.updateTagGroupByDTO(tagGroupDTO, tagGroup);
    }


    /**
     * 标签组添加标签
     * @param site
     * @param tagGroupId
     * @param tagIds
     */
    @PatchMapping("/{tagGroupId:\\d+}/tags")
    @LogRequired(operation = "'标签组' + #tagGroupId + '添加标签' + #tagIds")
    public TagGroup addTagsIntoTagGroup(@RequestAttribute("site") Site site, @PathVariable("tagGroupId") Long tagGroupId, @RequestBody List<Long> tagIds) {
        TagGroup tagGroup = tagGroupService.getTagGroupById(tagGroupId);
        if (tagGroup == null || tagGroup.getSite() != site) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "标签组不存在");
        }
        if (CollectionUtils.isEmpty(tagIds) || tagIds.contains(null)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "tagIds不能为空");
        }
        return tagGroupService.addTagsIntoTagGroup(tagGroup, tagIds, site);
    }


    /**
     * 标签组删除标签
     * @param site
     * @param tagGroupId
     * @param tagIds
     */
    @DeleteMapping("/{tagGroupId:\\d+}/tags")
    @LogRequired(operation = "'标签组' + #tagGroupId + '删除标签' + #tagIds")
    public TagGroup removeTagFromTagGroup(@RequestAttribute("site") Site site, @PathVariable("tagGroupId") Long tagGroupId, @RequestBody List<Long> tagIds) {
        TagGroup tagGroup = tagGroupService.getTagGroupById(tagGroupId);
        if (tagGroup == null || tagGroup.getSite() != site) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "标签组不存在");
        }
        if (CollectionUtils.isEmpty(tagIds) || tagIds.contains(null)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "tagIds不能为空");
        }
        return tagGroupService.removeTagFromTagGroup(tagGroup, tagIds, site);
    }
}
